package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoxiaode
 * @date 2021/10/3 20:25
 **/

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl  implements ArticleFreemarkerService  {


    @Autowired
    private ApArticleContentMapper artMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ArticleMapper articleMapper;
    /*
     * 生成静态文件长传到Minio中
     *
     * */
    @Async
    public void buildArticleToMinio(ApArticle apArticle, String content) {

        if(StringUtils.isNotBlank(content)) {
            // 通过freemarker 生成html文件
            Template template = null;
            StringWriter out = new StringWriter();
            try {
                template = configuration.getTemplate("article.ftl");
                // 数据模型
                Map<String, Object> contentData = new HashMap<>();
                contentData.put("content", JSON.parseArray(content));
                // 合成
                template.process(contentData, out);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // html文件上传到minio中
            InputStream input = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", input);


            System.out.println(path);

            //4.修改ap_article表，保存static_url字段
            ApArticle article = new ApArticle();
            article.setId(apArticle.getId());
            article.setStaticUrl(path);
            articleMapper.updateById(article);
        }
    }
}
